<?php
class model_order extends framework_base_model {
	//批量导入字段
	private static $_batch_keywords = array(
			'sales_name','sales_customer','agreement_no','produce_name','material','format',
			'agreement_weight','agreement_sign_date','agreement_date','arrive_date','schedul_date','order_weight','factory_weight','unorder_weight','transport','produce_address','author','editer'
		);
	private static $_betch_max = 299;
	/**
	 * @desc 添加订单
	 * @param array 
	 * @return number
	 */
	public static function orderAdd($data) {
    	if(!is_array($data)) {
    		return 0;
    	}
    	try{
    		$sql = "insert into `weixin_order` set ";
    		$binds = array();
    		foreach ($data as $k => $v) {
    			$sql .= '`' . $k . '`=:' . $k . ',';
    			$binds[':' . $k] = $v;
    		}
    		$sql .= 'raw_add_time=NOW()';
    		$arr=self::DB() -> dbh -> prepare($sql);
    		$rel = $arr->execute($binds);
    		if($rel == TRUE) {
    			return self::DB()->dbh->lastInsertId();
    		} else {
    			return 0;
    		}
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		return 0;
    	}
    }
    /*
     * 根据ID获取新闻内容
     */
    public static function getOrderInfoById($id) {
    	$info = array();
    	if(intval($id) <= 0) {
    		return $info;
    	}
    	$sql = "select * from `weixin_order` where order_id=:order_id and delete_flag = 0";
    	try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute(array(":order_id" => intval($id)));
    		$info = $st -> fetch();
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
    	return $info;
    }
    /**
     * @desc 更新订单内容
     * @param unknown $id
     * @param unknown $data
     * @return unknown|number
     */
    public static function updateOrderInfo($id,$data) {
    	try{
    		$sql = 'UPDATE `weixin_order` SET ';
    		$binds = array();
    		foreach ($data as $k => $v) {
    			$sql .= '`' . $k . '`=:' . $k . ',';
    			$binds[':' . $k] = $v;
    		}
    		$ids = implode(',',$id);
    		$sql = trim($sql,',');
    		$sql .= ' WHERE `order_id` in ('.$ids.')';
    		$stm=self::DB() -> dbh -> prepare($sql);
    		$rel = $stm->execute($binds);
    		$rowCount = $stm -> rowCount();
    		return $rowCount;
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		return false;
    	}
    }
    /**
     * 获取订单列表
     * @param number $nextNum
     * @param number $pagesize
     * @param unknown $condition
     * @return unknown|Ambigous <number, unknown>
     */
    public static function orderList($nextNum = 0,$pagesize = 0,$condition = array()) {
    	$sql = "select `order_id`,`sales_name`,`sales_customer`,`agreement_no`,`produce_name`,`material`,`format`,`agreement_weight`,`agreement_sign_date`,`agreement_date`,`arrive_date`,`schedul_date`,`order_weight`,`factory_weight`,`unorder_weight`,`transport`,`produce_address`,`editer`,`raw_update_time` from `weixin_order` where `delete_flag` = 0";
		$where = "";
    	if(is_array($condition)&& count($condition)>0){
    		if(isset($condition['sales_customer'])) {
    			$where .= " and sales_customer like '%{$condition['sales_customer']}%'";
    		}
			if(isset($condition['sales_name'])) {
    			$where .= " and sales_name like '%{$condition['sales_name']}%'";
    		}
			if(isset($condition['agreement_no'])) {
    			$where .= " and agreement_no like '%{$condition['agreement_no']}%'";
    		}
			if(isset($condition['produce_name'])) {
    			$where .= " and produce_name like '%{$condition['produce_name']}%'";
    		}
			if(isset($condition['material'])) {
    			$where .= " and material like '%{$condition['material']}%'";
    		}
			if(isset($condition['formatg'])) {
    			$where .= " and format like '%{$condition['formatg']}%'";
    		}
    	}
    	$where .= " order by `raw_add_time` desc";
    	$limit = "";
        if($pagesize != 0 ){
    		$limit = " limit {$nextNum},{$pagesize}";
    	}
    	$result = array();
    	try {
    		$st = self::DB()->dbh->prepare($sql.$where.$limit);
    		$st->execute();
    		$result = $st->fetchAll();
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		$result = array();
    	}
		
		$sql = "select count(*) from `weixin_order` where `delete_flag` = 0 {$where}";
		$binds2 = array();
    	try {
    		$st = self::DB()->dbh->prepare($sql);
    		$st->execute($binds2);
    		$count = $st->fetchColumn();
    		$result['count'] = $count;
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		$result['count'] = 0;
    	}		
		return $result;
    }
	/*
	* @desc 批量写入订单
	* @author kevin wang
	* @param array
	* @return boolean
	*
	*/
	public static function batch_insert_order(array $orders){
		if(empty($orders)){
			return false;
		}
		
		try{
			$sql = "";
			$bind = array();
			$i = 0;
			foreach($orders as $order){
				//$produce_id = self::getProduceByName($order[3]);
				$same = self::orderIsSame($order[2], $order[3], $order[4], $order[5]);
				if(!empty($same)){
					$sql .= "update `weixin_order` set ";
				}else{
					$sql .= "insert into `weixin_order` set ";
				}
				foreach($order as $k=>$v){
					$key = self::$_batch_keywords[$k];
					/*if($key == 'produce_id'){
						$parentid = self::getParentByName($v);
						$sql .= "`produce_class_id` = ?,";
						$bind[] = $parentid;
						$v = self::getProduceByName($v);
					}*/
					$sql .= "`{$key}` = ?,";
					$bind[] = $v;
				}
				if(!empty($same)){
					$sql = trim($sql, ',');
					$sql .= " where `order_id` = {$same['order_id']};";
				}else{
					$sql .= '`raw_add_time` = NOW();';
				}
				
				$i++;
				if($i > self::$_betch_max){
					$sqls[] = $sql;
					$binds[] = $bind;
					$bind = array();
					$sql = "";
					$i = 0;
				}
				
			}
			//处理最后一个
			if(!empty($sql)){
				$sqls[] = $sql;
				$binds[] = $bind;
			}

			$pdo = self::DB() -> dbh;

			foreach($sqls as $key => $sqlv){
				$stm = $pdo -> prepare($sqlv);
    			$stm -> execute($binds[$key]);
			}
			
			return true;
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		return false;
    	}
	}
	//获取产品名称
	public static function getProduceList(){
		$sql = "select `product_id`,`produce_name` from `weixin_product` where `delete_flag` = 0 and `status` = 0";
		$return = array();
    	try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute();
    		$info = $st -> fetchAll();
			if(!empty($info)){
				foreach($info as $value){
					$return[$value['product_id']] = $value['produce_name'];
				}
			}
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
		return $return;
	}
	//获取产品ID
	public static function getProduceByName($produce_name){
		$sql = "select `product_id` from `weixin_product` where `produce_name` = :produce_name and `delete_flag` = 0 and `status` = 0";
		$product_id = 0;
    	try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute(array(':produce_name' => $produce_name));
    		$product_id = $st -> fetchColumn();
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
		return $product_id;
	}
	//获取大类产品ID
	public static function getParentByName($produce_name){
		$sql = "select `parent_id` from `weixin_product` where `produce_name` = :produce_name and `delete_flag` = 0 and `status` = 0";
		$product_id = 0;
    	try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute(array(':produce_name' => $produce_name));
    		$product_id = $st -> fetchColumn();
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
		return $product_id;
	}
	//判断是否有相同的数据
	public static function orderIsSame($agreement_no, $produce_name, $material, $format){
		$sql = "select `order_id` from `weixin_order` where `agreement_no` = :agreement_no and `produce_name` = :produce_name and `material` = :material and `format` = :format and `delete_flag` = 0";
		$result = array();
		try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute(array(':agreement_no'=>$agreement_no,':produce_name'=>$produce_name,':material'=>$material,':format'=>$format));
    		$result = $st -> fetch();
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
		return $result;
	}
}
